#include "skywatcher.h"

/** Usart globals **/
volatile unsigned char cmd[32];        // receive buffer
volatile unsigned char usart_index=0;  // receive buffer index
volatile unsigned char usart_rdy=0;    // receive flag


void usart_open(unsigned int spbrg) 
{
  TXSTA = 0; // Reset USART registers to POR state
  RCSTA = 0;
  TXSTAbits.SYNC = 0; // Asynchronous mode
  RCSTAbits.SPEN = 1; // Enable Usart
  TXSTAbits.TX9 = 0;  // 8 bits TX
  RCSTAbits.RX9 = 0;  // 8 bits TX
  TXSTAbits.CSRC = 0; // No synchronous master mode
  RCSTAbits.SREN = 0; // No single receive
  /* RX interrupts */
  PIR1bits.RCIF = 0;
  PIE1bits.RCIE = 1;
  /* No TX interrupts */
//  PIR1bits.TXIF = 0;
  PIE1bits.TXIE = 0;
  TXSTAbits.BRGH = 1;
  SPBRG = (char)spbrg;
  RCSTAbits.CREN = 1; // Enable RX
  TXSTAbits.TXEN = 1; // Enable TX
 
}


void send_byte(unsigned char c) {
  while (PIR1bits.TXIF == 0);
  TXREG = c;
//  PIR1bits.TXIF = 0; 
} 

void send_string(char *s) {
  while (*s) {
    while (PIR1bits.TXIF == 0);
    TXREG = *s++;
//    PIR1bits.TXIF = 0; 
  }
}

char hexa[16] = {'0', '1', '2', '3', '4', '5', '6', '7', 
                 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
                
void send_u24(unsigned long n) {
   send_byte(hexa[(n & 0xF0) >> 4]);
   send_byte(hexa[(n & 0x0F)]);
   send_byte(hexa[(n & 0xF000) >> 12]);
   send_byte(hexa[(n & 0x0F00) >> 8]);
   send_byte(hexa[(n & 0xF00000) >> 20]);
   send_byte(hexa[(n & 0x0F0000) >> 16]);
}

void send_u12(unsigned int n) {
   send_byte(hexa[(n & 0xF0) >> 4]);
   send_byte(hexa[(n & 0x0F)]);
   send_byte(hexa[(n & 0xF00) >> 8]);
}

void send_u8(unsigned char n) {
   send_byte(hexa[(n & 0xF0) >> 4]);
   send_byte(hexa[(n & 0x0F)]);
}

#define HEX(c) (((c) < 'A')?((c)-'0'):((c) - 'A') + 10)
unsigned long get_u8(void) {
   unsigned long res = 0;
   res|=HEX(cmd[3]); res <<= 4;
   res|=HEX(cmd[4]); 
   return res;
}

unsigned long get_u24(void) {
   unsigned long res = 0;
   res=HEX(cmd[7]); res <<= 4;
   res|=HEX(cmd[8]); res <<= 4;
   res|=HEX(cmd[5]); res <<= 4;
   res|=HEX(cmd[6]); res <<= 4;
   res|=HEX(cmd[3]); res <<= 4;
   res|=HEX(cmd[4]); 
   return res;
}
